package whu.cn.whushare.db;

import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.androidplus.util.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class DBUtil {
    public final static File SD = Environment.getExternalStorageDirectory();
    final static String dbName = DbHelper.DATABASE_NAME;
    final static String Tag = "DBUtil";
    public final static String ROM_DB_PATH = Environment.getDataDirectory().getAbsolutePath() + "/data/whuhr/databases";

    private synchronized static boolean copyDB(File src, File target) {
        FileChannel srcChannel = null;
        FileChannel dstChannel = null;
        try {
            if (target.exists())
                target.delete();

            if (src.exists()) {
                srcChannel = new FileInputStream(src).getChannel();
                dstChannel = new FileOutputStream(target).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

            }

            return true;
        } catch (Exception e) {
            LogUtils.e(DBUtil.class.getSimpleName(), "error when backup whu.cn.whushare.db:" + e.getMessage());
            return false;
        } finally {
            try {
                if (srcChannel != null)
                    srcChannel.close();
                if (dstChannel != null)
                    dstChannel.close();
            } catch (IOException ignored) {
            }
        }
    }

    public static void checkDBVersion() {
        File file = new File(DBUtil.ROM_DB_PATH + DbHelper.DATABASE_NAME);
        if (file.exists()) {
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
            if (db.getVersion() > DbHelper.DATABASE_VERSION)
                file.delete();

            db.close();
        }
    }
}
